<template>
  <section class="padding EndWaybillList">
    <!-- 银行汇款(选择以下任何一帐号转账还款) -->
    <el-row>
      <el-col :xs="24" :sm="8" :md="6" :lg="6" :xl="6">
        <el-card shadow="always" class="text-center padding">
          <h2 class="text-red">当前欠款</h2>

          <div class="text-red">
            <span class="text-xxl">¥</span>
            <span class="text-xxl">{{ currentDebt }}</span>
            <!-- <span class="text-xl">.</span>
            <span class="text-xl">00</span> -->
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">银行汇款(选择以下任何一帐号转账还款)</span>
      </div>
      <TableModule
        :table-columns="tableColumns"
        :table-data="tableData"
        :table-operation="tableOperation"
        @clickOperation="operationList"
      />
    </el-card>

    <!-- <el-dialog title="还款信息" width="30%" :visible.sync="dialogFormVisible">
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
        size="mini"
        :model="form"
        class="padding-lr-40"
      >
        <el-form-item prop="email">
          <div slot="label">请上传水单: <font style="color:red">*</font></div>
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadFn"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              @click="handlePictureCardPreview($event)"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item prop="bankStatementAmount">
          <div slot="label">充值金额(RMB):</div>
          <el-input
            v-model="form.bankStatementAmount"
            placeholder="请填写充值金额(RMB)"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <div slot="label">备注:</div>
          <el-input
            v-model="form.customerRemark"
            placeholder="请填写备注"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetForm()">取消</el-button>
        <el-button @click="submitForm('ruleForm')">提交</el-button>
      </div>
    </el-dialog> -->
    <el-dialog title="还款信息" width="30%" :visible.sync="dialogFormVisible">
      <div class="">
        系统升级中请联系销售进行还款
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="充值信息" width="30%" :visible.sync="rechargeFormVisible">
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
        size="mini"
        :model="form"
        class="padding-lr-40"
      >
        <el-form-item prop="trxAmt">
          <div slot="label">充值金额(RMB):</div>
          <el-input
            v-model="bank.trxAmt"
            placeholder="请填写充值金额(RMB)"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="rechargeForm('ruleForm')"
          >充值</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog> -->
  </section>
</template>

<script>
import TableModule from '@/components/TableModule'
import { queryBank, saveRepayment } from '@/api/quickRepayment'
// import { getToken, setToken } from '@/utils/auth'
import request from '@/utils/request'
import { getInfo } from '@/api/user'
export default {
  name: 'QuickRepayment',
  components: {
    TableModule
  },
  data() {
    const isbankStatementAmount = (rule, value, callback) => {
      if (value !== '') {
        const reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
        if (reg.test(value)) {
          return callback()
        } else {
          return callback(new Error('请填写正确的数字（只能有2位小数）'))
        }
      } else {
        return callback(new Error('请填写充值金额'))
      }
    }

    return {
      currentDebt: '0.00',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      form: {
        rechargePicture: '',
        bankStatementAmount: '',
        customerRemark: ''
      },
      imageUrl: '',
      bank: {
        trxAmt: 0
      },
      dialogFormVisible: false,
      rechargeFormVisible: false,
      streetList: [],
      cityValue: [],
      currentPage: 1,
      searchCriteria: {
        customerDeliveryCompany: '',
        customerDeliveryAddressAttn: '',
        customerDeliveryAddressPhone: '',
        countryId: ''
      },
      tableColumns: [
        { prop: 'accountName', label: '户名' },
        { prop: 'bankName', label: '开户行' },
        { prop: 'address', label: '开户行地址' },
        { prop: 'accountNo', label: '帐号' }
      ],
      tableData: [],
      tableOperation: [
        {
          name: 'edit',
          tips: '还款',
          type: 'text',
          show: ['all']
        }
        //  {
        //    name: 'edit',
        //    tips: '充值',
        //    type: 'text',
        //    show: ['all']
        //  }
      ],
      rules: {
        bankStatementAmount: [
          { required: true, message: '请填充值金额', trigger: 'blur' },
          { validator: isbankStatementAmount, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.init()
    // console.log('params', this.$route.params)
    if (this.$route.params && this.$route.params.currentDebt) {
      this.currentDebt = this.$route.params.currentDebt
    } else {
      this.initCurrentDebt()
    }
  },
  methods: {
    async init() {
      this.$store.dispatch('app/toggleDialog', true)
      const dataList = await queryBank({})
      // console.log(dataList)
      this.tableData = dataList
      this.$store.dispatch('app/toggleDialog', false)
    },
    async initCurrentDebt() {
      const user = await getInfo({})
      if (user) {
        if (user.currentDebt && user.currentDebt !== 0) {
          this.currentDebt = user.currentDebt
        } else {
          this.currentDebt = '0.00'
        }
      }
    },
    operationList(data, name) {
      if (name.tips === '还款') {
        this.dialogFormVisible = true
        this.selectTd = data
      }
      if (name.tips === '充值') {
        this.rechargeFormVisible = true
        this.selectTd = data
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }

      this.imageUrl = window.URL.createObjectURL(file)
      return true
    },
    async submitForm(formName) {
      if (this.form.rechargePicture === '') {
        this.$message.error('请上传水单！')
        return false
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          // alert('submit!')
          this.saveData()
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    async saveData() {
      this.$store.dispatch('app/toggleDialog', true)

      const data = await saveRepayment(this.form)
      if (data.code === 200) {
        this.$message.success('还款成功！')
        this.resetForm()
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    resetForm() {
      this.form = {
        rechargePicture: '',
        bankStatementAmount: '',
        customerRemark: ''
      }
      this.imageUrl = ''
      this.dialogFormVisible = false
    },

    handlePictureCardPreview(e) {
      //  this.dialogImageUrl = file.url
      //  this.dialogVisible = true
      e.preventDefault()
      // console.log('12121212', e)
    },

    async uploadFn(params) {
      // console.log("params",params);
      if (!this.beforeAvatarUpload(params.file)) return
      this.$store.dispatch('app/toggleDialog', true)

      //  通过 FormData 对象上传文件
      var formData = new FormData()
      formData.append('file', params.file)
      // console.log(formData);
      const data = await request({
        url: '/finance/repayment/uploadSatementImage',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      // console.log('data', data)

      if (data.fileUrl) {
        this.form.rechargePicture = data.fileUrl
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    }
  }
}
</script>

<style scoped>
.EndWaybillList >>> .el-textarea__inner {
  min-height: 60px !important;
}
</style>

<style lang="scss" scoped>
.item {
  position: absolute;
  right: -25px;
  top: 3px;
  font-size: 20px;
}
.avatar-uploader {
  border: 1px solid #dcdfe6;
}
.avatar-uploader .el-upload {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
